from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from celery_tasks.static_html.tasks import get_detail_html
from goods.models import Brand


class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = '__all__'

        # 重写create方法,图片上传到fasdDFS中
    def create(self, validated_data):
        #         建立连接对象
        client = Fdfs_client(settings.FASRTDFS_PATH)
        #         获取数据
        request = self.context['request']
        logo_file = request.data.get('logo')
        #         上传图片
        res = client.upload_by_buffer(logo_file.read())
        #         判断返回结果
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        logo_url = res['Remote file_id']
        log = Brand.objects.create(logo=logo_url,name=request.data['name'],first_letter=request.data['first_letter'])
        return log

    def update(self, instance, validated_data):
        # 1、建立fasdDFS连接对象
        client = Fdfs_client(settings.FASRTDFS_PATH)
        # 2、获取图片数据 在序列化器中获取request对象
        request = self.context['request']
        logo_file = request.data.get('logo')
        # 3、上传图片
        res = client.upload_by_buffer(logo_file.read())
        # 4、判断返回结果
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 5、上传成功将返回的文件路径更新到图片表中
        logo_url = res['Remote file_id']
        instance.logo = logo_url
        instance.name = request.data['name']
        instance.first_letter = request.data['first_letter']
        instance.save()


        # 6、返回保存后的图片对象数据
        return instance
